// 提交订单

<template>
  <view>
    <view class="top">
      <!-- tabs -->
      <view class="tabs">
        <view :class="{ selected: postForm.diver_type === 2 }" @tap="postForm.diver_type = 2">
          到店自取
        </view>
        <view :class="{ selected: postForm.diver_type === 1 }" @tap="postForm.diver_type = 1">
          专业配送
        </view>
      </view>
      <!-- 配送方式 -->
      <view class="type">
        <!-- 自取地址 -->
        <view class="store" v-if="postForm.diver_type === 2 && storeDetail">
          <view class="store-left">
            <text class="iconfont icon-dianpu"></text>
          </view>
          <view class="store-right">
            <view class="right-top">
              <view class="store-address">
                {{ storeDetail.detail_address }}
              </view>
              <text class="iconfont icon-dizhi"></text>
            </view>
            <view class="right-bottom">
              <view class="store-phone" @tap="call(storeDetail.connect_mobile)">
                <text class="iconfont icon-dianhua"></text>
                <text class="phone">{{ storeDetail.connect_mobile }}</text>
              </view>
              <view class="store-change" @tap="toPage">
                <text>更改自取地址</text>
                <text class="iconfont icon-jiantou"></text>
              </view>
            </view>
          </view>
        </view>
        <!-- 收货地址 -->
        <view class="address" v-else-if="postForm.diver_type === 1 && addressDetail" @tap="toPage">
          <view class="address-left">
            <view v-if="addressDetail.is_default == 1">默认</view>
          </view>
          <view class="address-right">
            <view class="right-top">
              {{
                addressDetail.province_name +
                addressDetail.city_name +
                addressDetail.area_name +
                addressDetail.detail_address
              }}
            </view>
            <view class="right-bottom">
              <text>{{ addressDetail.connect_name }}</text>
              <text>{{ addressDetail.connect_mobile }}</text>
            </view>
          </view>
        </view>
        <view v-else @tap="toPage">
          <text>
            {{ postForm.diver_type === 2 ? '选择自取地址' : '选择收货地址' }}
          </text>
          <text class="iconfont icon-jiantou"></text>
        </view>
      </view>
    </view>

    <scroll-view class="center" :scroll-y="true">
      <!-- 商品 -->
      <view class="goods">
        <view class="item" v-for="item in cartList" :key="item.id">
          <view class="left">
            <view class="goods-image">
              <image
                :src="
                  item.goods.goods_image.startsWith('http')
                    ? item.goods.goods_image
                    : baseURL + item.goods.goods_image
                "
                mode="aspectFill"
              />
            </view>
            <view class="goods-info">
              <view class="goods-title">{{ item.goods.goods_name }}</view>
              <view class="goods-number">
                <text class="iconfont icon-cha"></text>
                <text>{{ item.number }}</text>
              </view>
            </view>
          </view>
          <view class="right" v-if="priceStatus">
            ￥{{ item.goods.price + '.' + item.goods.decimal }}
          </view>
        </view>
      </view>
      <!-- 列表 -->
      <view class="list">
        <!-- <view class="item">
          <view class="item-title">配送费</view>
          <view class="item-content">0</view>
        </view> -->
        <view class="item" v-if="openPay">
          <view class="item-title">支付方式</view>
          <view class="item-content">微信支付</view>
        </view>
        <view class="item" :style="{ borderBottom: priceStatus ? '' : 'none' }">
          <view class="item-title">配送方式</view>
          <view class="item-content">
            {{ postForm.diver_type === 2 ? '到店自取' : '专业配送' }}
          </view>
        </view>
      </view>
      <!-- 总价 -->
      <view class="total" v-if="priceStatus">
        <text class="text1">{{ openPay ? '需付款' : '合计' }}</text>
        <text class="text2">￥</text>
        <text class="text3">{{ totalPrice }}</text>
      </view>
    </scroll-view>

    <view class="bottom">
      <view class="pay" @tap="pay">{{ openPay ? '去支付' : '提交' }}</view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'

export default {
  data() {
    return {
      // 控制去支付显示
      isPay: false,
      // 是否开启支付
      openPay: false,
      baseURL: this.$baseURL,
      // 购物车列表
      cartList: [],
      // 总价
      totalPrice: 0,
      // 自取地址详情
      storeDetail: null,
      // 收货地址详情
      addressDetail: null,
      postForm: {
        // 购物车详情ID（多个用英文,拼接）
        cart_id: '',
        // 配送类型（1：专业配送，2：到店自取）
        diver_type: 2,
        // 用户收货地址
        address_id: '',
        // 门店ID（到店自提必须）
        store_id: ''
      }
    }
  },
  onLoad(options) {
    const ids = JSON.parse(options.ids)
    this.postForm.cart_id = ids.join(',')
    this.getOpenPay()
    this.getCartList(ids)
    this.getPriceStatus()
  },
  computed: {
    ...mapState(['priceStatus'])
  },
  methods: {
	// 是否显示价格
	async getPriceStatus() {
		// todo home/index抄过来的方法  暂时不知道做什么用
	},
    // 是否开启支付
    async getOpenPay() {
      const res = await this.$http.post('/api/kuerp/order/config/getSet', {
        name: 'pay_status'
      })
      if (res.code == 200 && res.data == 1) {
        this.openPay = true
      }
    },
    // 获取购物车列表
    async getCartList(ids) {
      const res = await this.$http.post('/api/kuerp/order/index/getCart')
      if (res.code == 200) {
        ids.forEach((p) => {
          res.data.forEach((c) => {
            if (p == c.id) {
              this.cartList.push(c)
              // this.totalPrice =
              //   Number(this.totalPrice) + c.number * (c.goods.price + '.' + c.goods.decimal)
              // this.totalPrice += '.' + c.goods.decimal
              const price = c.number * `${c.goods.price}.${c.goods.decimal}`
              this.totalPrice += price
            }
          })
        })
      }
    },
    // 选择自取地址 OR 收货地址
    toPage() {
      if (this.postForm.diver_type === 1) {
        uni.navigateTo({
          url: '/pages/my/commonFunction/address/index?type=submitOrder'
        })
      } else {
        uni.navigateTo({
          url: `/pages/shopping/store?id=${this.postForm.store_id}`
        })
      }
    },
    // 拨打电话
    call(phoneNumber) {
      uni.makePhoneCall({
        phoneNumber
      })
    },
    // 支付
    async pay() {
      if (this.isPay) return
      if (this.postForm.diver_type === 1) {
        // 专业配送
        if (!this.postForm.address_id) {
          return uni.showToast({
            title: '请选择收货地址',
            icon: 'none'
          })
        }
        delete this.postForm.store_id
      } else {
        // 到店自取
        if (!this.postForm.store_id) {
          return uni.showToast({
            title: '请选择自取地址',
            icon: 'none'
          })
        }
        delete this.postForm.address_id
      }

      // 创建订单
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      const res = await this.$http.post('/api/kuerp/order/index/createOrder', this.postForm)
      if (res.code == 200) {
        this.isPay = true
        if (this.openPay) {
          const res1 = await this.$http.post('/api/kuerp/order/index/wxpay', {
            order_num: res.data
          })
          uni.hideLoading()

          if (res1.code == 200) {
            uni.requestPayment({
              provider: 'wxpay',
              timeStamp: res1.data.config.timeStamp,
              nonceStr: res1.data.config.nonceStr,
              package: res1.data.config.package,
              signType: res1.data.config.signType,
              paySign: res1.data.config.paySign,
              success: (result) => {
                // console.log('支付成功', result)
                uni.showToast({
                  title: '支付成功',
                  icon: 'success',
                  mask: true
                })
                uni.$emit('refreshCategoryPage')
                setTimeout(() => {
                  uni.navigateTo({ url: '/pages/shopping/result' })
                }, 500)
              },
              fail: (error) => {
                // console.log('支付失败', error)
                uni.showToast({
                  title: '支付失败',
                  icon: 'error',
                  mask: true
                })
                uni.$emit('refreshCategoryPage')
                setTimeout(() => {
                  uni.navigateTo({ url: '/pages/my/order/index?current=0' })
                }, 500)
              }
            })
          }
        } else {
          uni.hideLoading()
          uni.showToast({
            title: '提交成功',
            icon: 'success',
            mask: true
          })
          uni.$emit('refreshCategoryPage')
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/shopping/result' })
          }, 500)
        }
      }
    }
  }
}
</script>

<style>
page {
  background-color: #f7f7f7;
}
</style>
<style lang="scss" scoped>
.top {
  padding: 20rpx 28rpx 0;
  background-color: #fff;
}

.center {
  max-height: calc(100vh - 606rpx);
  margin-top: 28rpx;
  padding: 0 28rpx;
  background-color: #fff;
  color: #111;
}

.bottom {
  margin-top: 92rpx;
  padding: 0 28rpx;
  .pay {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 92rpx;
    background: #f74444;
    border-radius: 50rpx;
    font-size: 32rpx;
    font-weight: 500;
    color: #ffffff;
  }
}

// tabs
.tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80rpx;
  padding: 0 8rpx;
  border-radius: 40rpx;
  border: 4rpx solid #f74444;
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  view {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 339rpx;
    height: 64rpx;
  }
  .selected {
    background: #f74444;
    border-radius: 40rpx;
    color: #ffffff;
  }
}

// 配送方式
.type {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 212rpx;
  font-size: 40rpx;
  color: #999999;
}
// 自取地址
.store {
  display: flex;
  width: 694rpx;
  .iconfont {
    font-size: 32rpx;
    color: #f74444;
  }
  .store-left {
    display: flex;
    align-items: flex-start;
    .icon-dianpu {
      margin-top: 6rpx;
    }
  }
  .store-right {
    display: flex;
    flex-direction: column;
    margin-left: 22rpx;
    width: 100%;
    .right-top {
      display: flex;
      justify-content: space-between;
      .store-address {
        width: 542rpx;
        font-size: 32rpx;
        color: #111111;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      .icon-dizhi {
        margin-top: 6rpx;
      }
    }
    .right-bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20rpx;
      .store-phone {
        .icon-dianhua {
        }
        .phone {
          margin-left: 8rpx;
          color: #111;
          font-size: 24rpx;
        }
      }
      .store-change {
        text {
          font-size: 28rpx;
        }
        .icon-jiantou {
          color: #999;
        }
      }
    }
  }
}
// 收货地址
.address {
  display: flex;
  width: 694rpx;
  .address-left {
    width: 80rpx;
    view {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 64rpx;
      height: 36rpx;
      background: #fe3d23;
      border-radius: 4rpx;
      font-size: 24rpx;
      color: #ffffff;
    }
  }

  .address-right {
    color: #111111;
    .right-top {
      width: 516rpx;
      font-size: 32rpx;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .right-bottom {
      margin-top: 8rpx;
      text {
        margin-right: 20rpx;
        font-size: 24rpx;
      }
    }
  }
}

// 商品
.goods {
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    &:first-child {
      margin-top: 28rpx;
    }
    &:nth-child(n + 2) {
      margin-top: 32rpx;
    }
    .left {
      display: flex;
      .goods-image {
        display: flex;
        margin-right: 20rpx;
        image {
          width: 120rpx;
          height: 120rpx;
          background: #d8d8d8;
          border-radius: 12rpx;
        }
      }
      .goods-info {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        width: 360rpx;
        .goods-title {
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        .goods-number {
          display: flex;
          align-items: center;
          .iconfont {
            margin-right: 4rpx;
            font-size: 16rpx;
            color: #111;
          }
        }
      }
    }
    .right {
      font-size: 32rpx;
    }
  }
}

// 列表
.list {
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 116rpx;
    border-bottom: 1px solid #dedede;
    .item-title {
      flex: 1;
    }
    .item-content {
      flex: 1;
      text-align: right;
    }
  }
}

// 总价
.total {
  height: 160rpx;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  .text1 {
    margin-right: 12rpx;
  }
  .text2 {
    color: #fe3d23;
  }
  .text3 {
    font-size: 32rpx;
    font-weight: 500;
    color: #fe3d23;
  }
}
</style>
